package top.lingkang.ciyuanwaf.service.impl;

import com.alibaba.fastjson2.JSONObject;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import top.lingkang.ciyuanwaf.constants.LogType;
import top.lingkang.ciyuanwaf.dao.LogDao;
import top.lingkang.ciyuanwaf.entity.LogEntity;
import top.lingkang.ciyuanwaf.service.LogService;
import top.lingkang.hibernate6.transaction.Transaction;

/**
 * @author lingkang
 * created by 2023/11/28
 */
@Component
public class LogServiceImpl implements LogService {
    @Inject
    private LogDao logDao;

    @Transaction
    @Override
    public void add(LogType type, String content) {
        LogEntity log = new LogEntity();
        log.setId(System.currentTimeMillis() + "");
        log.setType(type.code);
        if (content.length() > 2048)
            content = content.substring(0, 2048);
        log.setContent(content);
        if (Context.current() != null)
            log.setIp(Context.current().realIp());
        else
            log.setIp("-");
        logDao.saveOrUpdate(log);
    }

    @Transaction
    @Override
    public void file(LogType type, String path, long size) {
        LogEntity log = new LogEntity();
        log.setId(System.currentTimeMillis() + "");
        log.setType(type.code);
        JSONObject content = new JSONObject();
        content.put("path", path);
        content.put("size", size);
        String str = content.toJSONString();
        if (str.length() > 2048)
            str = str.substring(0, 2048);
        log.setContent(str);
        if (Context.current() != null)
            log.setIp(Context.current().realIp());
        else
            log.setIp("-");
        logDao.saveOrUpdate(log);
    }
}
